package com.wgke.bluetooth.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import android.view.animation.DecelerateInterpolator;

public class WheelView extends View {
    private Paint mPaint;
    private List<String> mData = new ArrayList<>();
    private int mSelectedPosition = 0;
    private float mItemHeight; // 每个选项的高度(dp)
    private float mTextSize; // 文字大小(sp)
    private int mTextColor = 0xFF888888; // 普通文字颜色
    private int mSelectedTextColor = 0xFF000000; // 选中文字颜色
    private float mLastY;
    private float mCurrentScrollOffset = 0;
    private ValueAnimator mScrollAnimator;
    private boolean mIsCyclic = true; // 是否循环滚动
    private OnItemSelectedListener mListener;
    private float mMaxTextSize; // 最大文字大小(选中状态)
    private float mMinTextSize; // 最小文字大小(边缘状态)
    private float mScaleFactor = 0.8f; // 文字缩放因子

    public interface OnItemSelectedListener {
        void onItemSelected(int position, String item);
    }

    public WheelView(Context context) {
        super(context);
        init(context);
    }

    public WheelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        // 默认值设置为dp/sp单位
        mItemHeight = dpToPx(context, 50); // 50dp
        mTextSize = spToPx(context, 18); // 18sp
        mMaxTextSize = spToPx(context, 22); // 22sp
        mMinTextSize = spToPx(context, 14); // 14sp

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(mTextSize);
        mPaint.setTextAlign(Paint.Align.CENTER);

        // 测试数据
        for (int i = 0; i < 10; i++) {
            mData.add("Item " + i);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float centerY = getHeight() / 2f + mCurrentScrollOffset;

        for (int i = 0; i < mData.size(); i++) {
            float y = centerY + (i - mSelectedPosition) * mItemHeight;

            // 只绘制可见区域内的item
            if (y > -mItemHeight && y < getHeight() + mItemHeight) {
                // 计算距离中心的相对位置(0-1)
                float distanceFromCenter = Math.abs(y - getHeight() / 2f);
                float maxDistance = getHeight() / 2f;
                float ratio = Math.min(1, distanceFromCenter / maxDistance);

                // 根据距离计算文字大小
                float textSize = mMaxTextSize - (mMaxTextSize - mMinTextSize) * ratio;
                mPaint.setTextSize(textSize);

                // 计算透明度，离中心越远越透明
                float alpha = 1 - ratio * 0.8f; // 保留20%的最小透明度
                mPaint.setAlpha((int) (alpha * 255));

                // 设置颜色
                mPaint.setColor(i == mSelectedPosition ? mSelectedTextColor : mTextColor);

                // 绘制文本
                canvas.drawText(mData.get(i), getWidth() / 2f, y, mPaint);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = event.getY();
                cancelAnimation();
                return true;

            case MotionEvent.ACTION_MOVE:
                float deltaY = event.getY() - mLastY;
                mCurrentScrollOffset += deltaY;
                mLastY = event.getY();
                updateSelectedPosition();
                invalidate();
                return true;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                adjustPosition();
                return true;
        }
        return super.onTouchEvent(event);
    }

    private void updateSelectedPosition() {
        // 计算理论上的选中位置(可能超出边界)
        int theoreticalPos = (int) (-mCurrentScrollOffset / mItemHeight + 0.5f);

        if (mIsCyclic && !mData.isEmpty()) {
            // 循环滚动处理
            while (theoreticalPos < 0) {
                theoreticalPos += mData.size();
                mCurrentScrollOffset += mData.size() * mItemHeight;
            }
            while (theoreticalPos >= mData.size()) {
                theoreticalPos -= mData.size();
                mCurrentScrollOffset -= mData.size() * mItemHeight;
            }
            mSelectedPosition = theoreticalPos;
        } else {
            // 非循环滚动处理
            mSelectedPosition = Math.max(0, Math.min(mData.size() - 1, theoreticalPos));
        }
    }
    private void adjustPosition() {
        float targetOffset = -mSelectedPosition * mItemHeight;
        startScrollAnimation(targetOffset);
    }

    private void startScrollAnimation(float targetOffset) {
        cancelAnimation();

        mScrollAnimator = ValueAnimator.ofFloat(mCurrentScrollOffset, targetOffset);
        mScrollAnimator.setDuration(300);
        mScrollAnimator.setInterpolator(new DecelerateInterpolator());
        mScrollAnimator.addUpdateListener(animation -> {
            mCurrentScrollOffset = (float) animation.getAnimatedValue();
            invalidate();
        });
        mScrollAnimator.start();

        // 滚动结束后回调
        if (mListener != null) {
            postDelayed(() -> mListener.onItemSelected(mSelectedPosition, mData.get(mSelectedPosition)), 300);
        }
    }

    private void cancelAnimation() {
        if (mScrollAnimator != null && mScrollAnimator.isRunning()) {
            mScrollAnimator.cancel();
        }
    }

    // 单位转换方法
    private float dpToPx(Context context, float dp) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp,
                context.getResources().getDisplayMetrics());
    }

    private float spToPx(Context context, float sp) {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP,
                sp,
                context.getResources().getDisplayMetrics());
    }

    // 公共方法
    public void setData(List<String> data) {
        mData = data;
        mSelectedPosition = 0;
        mCurrentScrollOffset = 0;
        invalidate();
    }

    public String getSelectedItem() {
        return mData.get(mSelectedPosition);
    }

    public int getSelectedPosition() {
        return mSelectedPosition;
    }

    public void setCyclic(boolean cyclic) {
        mIsCyclic = cyclic;
    }

    public void setOnItemSelectedListener(OnItemSelectedListener listener) {
        mListener = listener;
    }

    public void setItemHeight(float heightDp) {
        mItemHeight = dpToPx(getContext(), heightDp);
        invalidate();
    }

    public void setTextSize(float sizeSp) {
        mTextSize = spToPx(getContext(), sizeSp);
        mMaxTextSize = mTextSize;
        mMinTextSize = mTextSize * 0.7f;
        mPaint.setTextSize(mTextSize);
        invalidate();
    }

    public void setTextColor(int normalColor, int selectedColor) {
        mTextColor = normalColor;
        mSelectedTextColor = selectedColor;
        invalidate();
    }
}